<template>
  <div class="student-management">
    
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="注册邮箱">
          <el-input v-model="searchForm.email" placeholder="请输入注册邮箱" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="注册时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="账户状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" style="width: 140px;">
            <el-option label="全部" value="" />
            <el-option label="正常" value="active" />
            <el-option label="临时锁定" value="locked" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <span>学生列表</span>
          <el-button type="primary" @click="handleRefresh">刷新</el-button>
        </div>
      </template>
      
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="studentUserId" label="学生ID" min-width="10%" />
        <el-table-column prop="email" label="注册邮箱" min-width="20%" />
        <el-table-column label="姓名" min-width="12%">
          <template #default="scope">
            <div v-if="scope.row.fullName" style="display: flex; align-items: center; gap: 8px;">
              <span>{{ scope.row.fullName }}</span>
              <el-tag type="success" size="small">简历</el-tag>
            </div>
            <el-tag v-else type="warning" size="small">简历未上传</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="注册时间" min-width="15%">
          <template #default="scope">
            {{ formatDateTime(scope.row.registrationTime) }}
          </template>
        </el-table-column>
        <el-table-column label="最近登录时间" min-width="15%">
          <template #default="scope">
            <span v-if="scope.row.lastLoginTime">{{ formatDateTime(scope.row.lastLoginTime) }}</span>
            <span v-else style="color: #999;">未登录</span>
          </template>
        </el-table-column>
        <el-table-column label="账户状态" min-width="10%">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.accountStatus)">
              {{ getStatusText(scope.row.accountStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="偏好语言" min-width="12%">
          <template #default="scope">
            <span v-if="scope.row.preferredLanguage === 'zh-CN'">中文</span>
            <span v-else-if="scope.row.preferredLanguage === 'en-US'">English</span>
            <span v-else style="color: #999;">-</span>
          </template>
        </el-table-column>
        <el-table-column label="是否验证" min-width="10%">
          <template #default="scope">
            <el-tag :type="scope.row.emailVerified ? 'success' : 'danger'" size="small">
              {{ scope.row.emailVerified ? '已验证' : '未验证' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="15%">
          <template #default="scope">
            <el-button type="info" size="small" @click="handleViewDetail(scope.row)">
              查看详情
            </el-button>
            <el-button 
              v-if="scope.row.accountStatus === 'active'"
              type="warning" 
              size="small" 
              @click="handleLock(scope.row)"
            >
              锁定
            </el-button>
            <el-button 
              v-if="scope.row.accountStatus === 'locked'"
              type="success" 
              size="small" 
              @click="handleUnlock(scope.row)"
            >
              解锁
            </el-button>
            <el-button 
              v-if="scope.row.accountStatus === 'active'"
              type="danger" 
              size="small" 
              @click="handleDisable(scope.row)"
            >
              禁用
            </el-button>
            <el-button 
              v-if="scope.row.accountStatus === 'disabled'"
              type="success" 
              size="small" 
              @click="handleEnable(scope.row)"
            >
              解封
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="学生详情"
      width="70%"
    >
      <div v-if="currentDetail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="姓名">
            <span v-if="currentDetail.fullName">{{ currentDetail.fullName }}</span>
            <el-tag v-else type="warning" size="small">简历未上传</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="姓">
            <span v-if="currentDetail.xing">{{ currentDetail.xing }}</span>
            <span v-else style="color: #999;">未填写</span>
          </el-descriptions-item>
          <el-descriptions-item label="名">
            <span v-if="currentDetail.ming">{{ currentDetail.ming }}</span>
            <span v-else style="color: #999;">未填写</span>
          </el-descriptions-item>
          <el-descriptions-item label="性别">
            <span v-if="currentDetail.gender === 'male'">男</span>
            <span v-else-if="currentDetail.gender === 'female'">女</span>
            <span v-else style="color: #999;">未填写</span>
          </el-descriptions-item>
          <el-descriptions-item label="国籍">{{ currentDetail.nationality || '未填写' }}</el-descriptions-item>
          <el-descriptions-item label="出生日期">
            <span v-if="currentDetail.dateOfBirth">{{ formatDate(currentDetail.dateOfBirth) }}</span>
            <span v-else style="color: #999;">未填写</span>
          </el-descriptions-item>
          <el-descriptions-item label="手机号">
            <span v-if="currentDetail.phoneNumber">{{ currentDetail.phoneNumber }}</span>
            <span v-else style="color: #999;">未填写</span>
          </el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ currentDetail.email }}</el-descriptions-item>
          <el-descriptions-item label="微信/WhatsApp">
            <span v-if="currentDetail.wechatWhatsapp">{{ currentDetail.wechatWhatsapp }}</span>
            <span v-else style="color: #999;">未填写</span>
          </el-descriptions-item>
          <el-descriptions-item label="简历状态">
            <el-tag :type="getResumeStatusType(currentDetail.resumeStatus)" size="small">
              {{ getResumeStatusText(currentDetail.resumeStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="最后更新时间">
            <span v-if="currentDetail.lastUpdateTime">{{ formatDateTime(currentDetail.lastUpdateTime) }}</span>
            <span v-else style="color: #999;">-</span>
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 简历内容 -->
        <div class="detail-section" v-if="currentDetail.resumeContent">
          <h4>简历内容</h4>
          <div class="resume-content" v-html="currentDetail.resumeContent"></div>
        </div>
        
        <!-- 驳回原因 -->
        <div class="detail-section" v-if="currentDetail.rejectionReason">
          <h4>驳回原因</h4>
          <p style="color: #f56c6c;">{{ currentDetail.rejectionReason }}</p>
        </div>
      </div>
    </el-dialog>
    

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getStudentList, getStudentDetail, lockStudent, unlockStudent, disableStudent, enableStudent } from '@/api/studentManage'

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const detailDialogVisible = ref(false)
const currentDetail = ref(null)

const searchForm = reactive({
  email: '',
  name: '',
  dateRange: [],
  status: ''
})

const tableData = ref([])

const getStatusType = (status) => {
  const statusMap = {
    active: 'success',
    locked: 'warning',
    disabled: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    active: '正常',
    locked: '临时锁定',
    disabled: '禁用'
  }
  return statusMap[status] || '未知'
}

const getResumeStatusType = (status) => {
  const statusMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return statusMap[status] || 'info'
}

const getResumeStatusText = (status) => {
  const statusMap = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已驳回'
  }
  return statusMap[status] || '未知'
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

// 原始数据
const originalData = ref([])

// 获取学生列表
const fetchStudentList = async () => {
  try {
    loading.value = true
    const response = await getStudentList()
    
    if (response.code === 200) {
      originalData.value = response.data
      applyFilters() // 应用筛选
    } else {
      ElMessage.error(response.message || '获取学生列表失败')
    }
  } catch (error) {
    console.error('获取学生列表失败:', error)
    ElMessage.error('获取学生列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 应用筛选
const applyFilters = () => {
  let filteredData = [...originalData.value]
  
  // 邮箱筛选
  if (searchForm.email) {
    filteredData = filteredData.filter(item => 
      item.email.toLowerCase().includes(searchForm.email.toLowerCase())
    )
  }
  
  // 姓名筛选
  if (searchForm.name) {
    filteredData = filteredData.filter(item => 
      item.fullName && item.fullName.toLowerCase().includes(searchForm.name.toLowerCase())
    )
  }
  
  // 注册时间筛选
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    const startDate = new Date(searchForm.dateRange[0])
    const endDate = new Date(searchForm.dateRange[1])
    endDate.setHours(23, 59, 59, 999) // 设置到当天结束
    
    filteredData = filteredData.filter(item => {
      const registrationDate = new Date(item.registrationTime)
      return registrationDate >= startDate && registrationDate <= endDate
    })
  }
  
  // 账户状态筛选
  if (searchForm.status) {
    filteredData = filteredData.filter(item => 
      item.accountStatus === searchForm.status
    )
  }
  
  tableData.value = filteredData
  total.value = filteredData.length
}

const handleSearch = () => {
  applyFilters()
}

const handleReset = () => {
  searchForm.email = ''
  searchForm.name = ''
  searchForm.dateRange = []
  searchForm.status = ''
  applyFilters()
}

const handleRefresh = () => {
  fetchStudentList()
}

const handleViewDetail = async (row) => {
  try {
    const response = await getStudentDetail(row.studentUserId)
    
    if (response.code === 200) {
      currentDetail.value = response.data
      detailDialogVisible.value = true
    } else {
      ElMessage.error(response.message || '获取学生详情失败')
    }
  } catch (error) {
    console.error('获取学生详情失败:', error)
    ElMessage.error('获取学生详情失败，请检查网络连接')
  }
}



const handleLock = (row) => {
  ElMessageBox.confirm(
    '确定要临时锁定该学生账户吗？锁定后学生将无法登录系统，15分钟后自动解锁。',
    '确认临时锁定',
    {
      confirmButtonText: '确定锁定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await lockStudent(row.studentUserId)
      
      if (response.code === 200) {
        ElMessage.success(response.message || '学生账户已锁定')
        fetchStudentList() // 刷新列表
      } else {
        ElMessage.error(response.message || '锁定失败')
      }
    } catch (error) {
      console.error('锁定学生账户失败:', error)
      ElMessage.error('锁定失败，请重试')
    }
  })
}

const handleUnlock = (row) => {
  ElMessageBox.confirm(
    '确定要解锁该学生账户吗？解锁后学生将可以正常登录系统。',
    '确认解锁',
    {
      confirmButtonText: '确定解锁',
      cancelButtonText: '取消',
      type: 'success'
    }
  ).then(async () => {
    try {
      const response = await unlockStudent(row.studentUserId)
      
      if (response.code === 200) {
        ElMessage.success(response.message || '学生账户已解锁')
        fetchStudentList() // 刷新列表
      } else {
        ElMessage.error(response.message || '解锁失败')
      }
    } catch (error) {
      console.error('解锁学生账户失败:', error)
      ElMessage.error('解锁失败，请重试')
    }
  })
}

const handleDisable = (row) => {
  ElMessageBox.confirm(
    '确定要禁用该学生账户吗？禁用后学生将无法登录系统。',
    '确认禁用',
    {
      confirmButtonText: '确定禁用',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await disableStudent(row.studentUserId)
      
      if (response.code === 200) {
        ElMessage.success('学生账户已禁用')
        fetchStudentList() // 刷新列表
      } else {
        ElMessage.error(response.message || '禁用失败')
      }
    } catch (error) {
      console.error('禁用学生账户失败:', error)
      ElMessage.error('禁用失败，请重试')
    }
  })
}

const handleEnable = (row) => {
  ElMessageBox.confirm(
    '确定要解封该学生账户吗？解封后学生将可以正常登录系统。',
    '确认解封',
    {
      confirmButtonText: '确定解封',
      cancelButtonText: '取消',
      type: 'success'
    }
  ).then(async () => {
    try {
      const response = await enableStudent(row.studentUserId)
      
      if (response.code === 200) {
        ElMessage.success('学生账户已解封')
        fetchStudentList() // 刷新列表
      } else {
        ElMessage.error(response.message || '解封失败')
      }
    } catch (error) {
      console.error('解封学生账户失败:', error)
      ElMessage.error('解封失败，请重试')
    }
  })
}

const handleSizeChange = (val) => {
  pageSize.value = val
  // 前端筛选不需要重新获取数据
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // 前端筛选不需要重新获取数据
}

onMounted(() => {
  fetchStudentList()
})
</script>

<style scoped>
.student-management {
  padding: 0;
  width: 100%;
  min-height: 100%;
  box-sizing: border-box;
}

.student-management h2 {
  margin-bottom: 20px;
  color: #333;
}

.search-card {
  margin-bottom: 20px;
  width: 100%;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-card {
  margin-bottom: 20px;
  width: 100%;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.detail-section {
  margin-top: 20px;
}

.resume-content {
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  padding: 16px;
  margin-top: 8px;
  max-height: 300px;
  overflow-y: auto;
}

.resume-content p {
  margin: 0 0 8px 0;
  line-height: 1.6;
}

.resume-content:last-child p {
  margin-bottom: 0;
}

.detail-section h4 {
  margin-bottom: 10px;
  color: #333;
}

.detail-section p {
  color: #666;
  line-height: 1.6;
}
</style> 